﻿using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using Vue.Admin.Common;
using Vue.Admin.Models;

namespace Vue.Admin.Tools
{
    public class JwtHelper
	{
		public static string CreatToken(JwtSettings jwtSettings, UserDataDto dataDto)
		{
			var claim = new Claim[]{
					new Claim(ClaimTypes.Name,dataDto.UserName),
					new Claim(ClaimTypes.Role,dataDto.UserRoleName)
				};

			//对称秘钥
			var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey));
			//签名证书(秘钥，加密算法)
			var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

			//生成token  [注意]需要nuget添加Microsoft.AspNetCore.Authentication.JwtBearer包，并引用System.IdentityModel.Tokens.Jwt命名空间
			var token = new JwtSecurityToken(
				jwtSettings.Issuer,
				jwtSettings.Audience,
				claim,
				DateTime.Now,
				DateTime.Now.AddMinutes(10),
				creds);

			string encodeToken = new JwtSecurityTokenHandler().WriteToken(token);
			return encodeToken;

		}
	}
}
